package com.yuanhua.xcxmng.wechat.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.yuanhua.xcxmng.wechat.cache.LocalCache;
import com.yuanhua.xcxmng.wechat.cons.AlertValue;
import com.yuanhua.xcxmng.wechat.cons.TestTypeEnum;
import com.yuanhua.xcxmng.wechat.entity.*;
import com.yuanhua.xcxmng.wechat.service.MyService;
import com.yuanhua.xcxmng.wechat.service.UserDataService;
import com.yuanhua.xcxmng.wechat.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/wechat/test/mx")
public class TestSecondControoler extends BaseController {

    @Autowired
    private WxMaService     wxService;

    @Autowired
    private MyService       myService;

    @Autowired
    private UserDataService userDataService;

    @GetMapping("report")
    public String report(String threeSession, int type, int cqch) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String openId = StringUtils.split(sessionCode, "^#^")[1];
        List<ReportDouble> result = Lists.newArrayList();
        try {
            Date now = new Date();
            Date before30 = DateUtil.offsetDay(now, -60);
            List<String> categories = Lists.newArrayList();

            TestTypeEnum typeEnum = TestTypeEnum.getEnumByCode(type);

            ReportDouble report = new ReportDouble();
            List<UserData> data = Lists.newArrayList();
            UserDataQuery param = new UserDataQuery();
            param.setOpenId(openId);
            param.setClType(typeEnum.getCode());
            param.setStartDate(before30);
            param.setEndDate(now);
            param.setCqch(cqch);
            data = userDataService.queryReport(param);
            List<Double> target = Lists.newArrayList();
            UserTarget userTarget = myService.findTargetByOpenId(openId);
            report.setCategories(categories);
            List<Double> doubles = Lists.newArrayList();
            data.stream().forEach(x -> isAdd(doubles, categories, target, userTarget, typeEnum, cqch, x));
            report.setData(doubles);
            report.setTarget(target);
            return JsonUtils.toJson(report);
        } catch (Exception e) {
            logger.error("[查询测量结果报表出错]:openid:" + openId, e, e.getMessage());
            return "fail";
        }
    }

    private void isAdd(List<Double> doubles, List<String> categories, List<Double> targetList, UserTarget target, TestTypeEnum type, int cqch, UserData x) {
        doubles.add(x.getZhi().doubleValue());
        categories.add(DateUtil.format(x.getCreateTime(), "MM-dd HH:mm:ss"));
        if (type == TestTypeEnum.Blood_Sugar) {
            if (cqch == 0) {
                targetList.add(target != null ? target.getTargetXtCq().doubleValue() : 0);
            } else {
                targetList.add(target != null ? target.getTargetXtCh().doubleValue() : 0);
            }
        } else if (type == TestTypeEnum.Uric_Acid) {
            targetList.add(target != null ? target.getTargetNs().doubleValue() : 0);
        } else if (type == TestTypeEnum.Cholesterol) {
            targetList.add(target != null ? target.getTargetDgc().doubleValue() : 0);
        } else if (type == TestTypeEnum.Triglyceride) {
            targetList.add(target != null ? target.getTargetGysz().doubleValue() : 0);
        }
    }

    @GetMapping("list")
    public String list(String threeSession, int type, int next, int cqch) {
        // 用户信息校验
        if (StringUtils.isBlank(threeSession)) {
            return "empty threeSession";
        }
        String sessionCode = LocalCache.getInStance().getLocalCache(threeSession);
        if (StringUtils.isBlank(sessionCode)) {
            return "fail";
        }
        String openId = StringUtils.split(sessionCode, "^#^")[1];

        try {
            TestTypeEnum typeEnum = TestTypeEnum.getEnumByCode(type);
            UserDataQuery param = new UserDataQuery();
            param.setOpenId(openId);
            param.setClType(typeEnum.getCode());
            param.setCqch(cqch);
            List<UserData> userDataList = userDataService.queryPage(param, next);
            UserTarget userTarget = myService.findTargetByOpenId(openId);
            User user = myService.findUserByOpenId(openId);
            List<DetailItem> list = Lists.newArrayList();
            userDataList.stream().forEach(x -> {
                DetailItem item = new DetailItem();
                item.setDate(DateUtil.format(x.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                item.setZhi(x.getZhi().doubleValue());
                if (userTarget != null) {
                    if (typeEnum == TestTypeEnum.Blood_Sugar) {
                        if (cqch == 0) {
                            double cqxt = userTarget.getTargetXtCq().doubleValue();
                            if (x.getZhi().doubleValue() < AlertValue.CQXT_VALUE) {
                                item.setSsxj(1);
                            } else if (x.getZhi().doubleValue() > cqxt) {
                                item.setSsxj(2);
                            } else {
                                //正常
                                item.setSsxj(0);
                            }
                        } else {
                            double chxt = userTarget.getTargetXtCh().doubleValue();
                            if (x.getZhi().doubleValue() < AlertValue.CHXT_VALUE) {
                                item.setSsxj(1);
                            } else if (x.getZhi().doubleValue() > chxt) {
                                item.setSsxj(2);
                            } else {
                                item.setSsxj(0);
                            }
                        }
                    } else if (typeEnum == TestTypeEnum.Uric_Acid) {
                        double ns = userTarget.getTargetNs().doubleValue();
                        if (x.getZhi().doubleValue() < (user.getGender() == 1 ? AlertValue.NS_M_VALUE : AlertValue.NS_W_VALUE)) {
                            item.setSsxj(1);
                        } else if (x.getZhi().doubleValue() > ns) {
                            item.setSsxj(2);
                        } else {
                            item.setSsxj(0);
                        }
                        item.setDw("umol/L");
                    } else if (typeEnum == TestTypeEnum.Cholesterol) {
                        double dgc = userTarget.getTargetDgc().doubleValue();
                        if (x.getZhi().doubleValue() < AlertValue.DGC_VALUE) {
                            item.setSsxj(1);
                        } else if (x.getZhi().doubleValue() > dgc) {
                            item.setSsxj(2);
                        }
                    } else if (typeEnum == TestTypeEnum.Triglyceride) {
                        double gysz = userTarget.getTargetGysz().doubleValue();
                        if (x.getZhi().doubleValue() > gysz) {
                            item.setSsxj(2);
                        }
                    }
                }
                list.add(item);
            });
            return JsonUtils.toJson(list);
        } catch (Exception e) {
            logger.error("[查询测量结果列表出错]:openid:" + openId);
            return "fail";
        }
    }

    private void setBlod(List<UserData> blood) {
        if (CollectionUtil.isNotEmpty(blood)) {
            for (UserData userData : blood) {
                userData.setYear(DateUtil.year(userData.getCreateTime()));
                userData.setMonth(DateUtil.month(userData.getCreateTime()) + 1);
                userData.setDay(DateUtil.dayOfMonth(userData.getCreateTime()));
                userData.setHhmm(DateUtil.format(userData.getCreateTime(), "HH:mm") + "     ");
                userData.setStrcqch(userData.getCqch() == 0 ? "餐前" : "餐后");

            }
        }
    }

    private void setData(List<UserData> uric) {
        if (CollectionUtil.isNotEmpty(uric)) {
            for (UserData userData : uric) {
                userData.setYear(DateUtil.year(userData.getCreateTime()));
                userData.setMonth(DateUtil.month(userData.getCreateTime()) + 1);
                userData.setDay(DateUtil.dayOfMonth(userData.getCreateTime()));
                userData.setHhmm(DateUtil.format(userData.getCreateTime(), "HH:mm") + "     ");
            }
        }
    }
}
